<?php
	require_once ("../../config.php");	

	# Verify what button was clicked.
	$btaction = $_POST["submit_unitfind"];
	
	if ($btaction == "Voltar"){
		header("Location: /itcontrol/com/main/main.php");
	}else{	
		
		# Get data previous inserted
		$name = $_POST["input_nameUnit"];
		$cnpj = $_POST["input_cnpj"];
		$city = $_POST["input_city"];
		
		$fields[0] = "nameUnit";
		$fields[1] = "cnpj";
		$fields[2] = "uf_id";
		
		$namefields[0] = "Unidade";
		$namefields[1] = "CNPJ";
		$namefields[2] = "Cidade";
		
		$dbconnection = new connectDB();
		
		$count = 0;
		
		# Check if there is some empty field
		if(!empty($name)){	
			$where[$count] = "tb_unit." . $fields[0]. "='" .$name. "'";
			$count = $count + 1;
		}
		
		if(!empty($cnpj)){
			$where[$count] = "tb_unit." . $fields[1]. "='" .$cnpj. "'";
			$count = $count + 1;
		}
		
		if(!empty($city)){
			
			$fieldsOpt[0] = "id";
			
			$namefieldsOpt[0] = "ID";
			
			$whereOpt[0] = "city = '" .$city. "'";
			$query = mysql_query($dbconnection->selectDB("tb_uf", "uf", "find", $fieldsOpt, $namefieldsOpt, $whereOpt));
			$result = mysql_fetch_array($query);
			
			$city = $result[0];
			
			$where[$count] = "tb_unit." . $fields[2]. "='" .$city. "'";
			$count = $count + 1;
		}
		
		#$query = mysql_query($dbconnection->selectDBLeftJoin("tb_unit", "unit", "find", $fields, $namefields, "tb_uf", $on, $where));

		#$query = mysql_fetch_array($query);
		
		$values = urlencode(implode(",", $where));
		
		$dbconnection->disconnectDB();
		
		header("Location: /itcontrol/com/main/unit/unit_list.php?return=" .$values);
		
	}
?>